#include "ClientThread.h"
#include "Constants.h"
#include "SocketImpl.h"
#include "SMTPSessionManager.h"
#include "ServerThread.h"

#include <log4cpp/Category.hh>

namespace ClientThread
{

log4cpp::Category& logger = log4cpp::Category::getInstance(
    std::string(SERVER_LOGGER));

ClientThread::ClientThread(int fd, ServerThread::ServerThread& server):ThreadPool::WorkerTask(),
    _clientFd(fd), _server(server)
{
}

ClientThread::~ClientThread()
{

}

void ClientThread::run()
{
  Constants::setThreadID(_threadID);

  handleConnection();

  //close connection
  //close(_clientFd);

  //notify Server about done
  //_server.msgStatus();
}

void ClientThread::handleConnection()
{

  LOG_DEBUG(_threadID + "ClientThread::handleConnection->In");

  try
  {
    bool done = false;
    std::unique_ptr<SMTP::SMTPSessionManager> smtp(
        new SMTP::SMTPSessionManager());
    SocketImp::writeData(_clientFd, smtp->greetMessage());

    while (!done)
    {

      std::stringstream ss;
      int n = SocketImp::readData(_clientFd, ss);
      if (n <= 0)
        done = true;
      else
      {

        std::stringstream lm;
        lm << _threadID << " : " << ss.str() << ":" << ss.str().length();

        std::string out = smtp->processCommand(ss.str());

        SocketImp::writeData(_clientFd, out);

        if (out == "221 goodbye")
          done = true;
      }
    }

    close(_clientFd);

    _server.msgStatus(smtp->getMsgCount());



    //notify Server that email connection is processed
  } catch (std::exception& ex)
  {
    LOG_ERROR(
        _threadID + std::string("> handleConnection failed: ") + ex.what());
  }

  LOG_DEBUG(_threadID + "ClientThread::handleConnection->Out");
}

}
